import React, { useEffect } from 'react';
import { Row, Col, Card, Statistic, Table, Tag, Button, Space } from 'antd';
import {
  RocketOutlined,
  UserOutlined,
  BookOutlined,
  DollarOutlined,
  PlusOutlined,
} from '@ant-design/icons';
import { useDispatch, useSelector } from 'react-redux';
import { useNavigate } from 'react-router-dom';
import { fetchFlights } from '../../store/slices/flightSlice';
import { fetchPassengers } from '../../store/slices/passengerSlice';
import { fetchBookings } from '../../store/slices/bookingSlice';

const Dashboard = () => {
  const dispatch = useDispatch();
  const navigate = useNavigate();
  const { flights } = useSelector((state) => state.flights);
  const { passengers } = useSelector((state) => state.passengers);
  const { bookings } = useSelector((state) => state.bookings);

  useEffect(() => {
    dispatch(fetchFlights());
    dispatch(fetchPassengers());
    dispatch(fetchBookings());
  }, [dispatch]);

  // 计算统计数据
  const totalFlights = flights.length;
  const totalPassengers = passengers.length;
  const totalBookings = bookings.length;
  const totalRevenue = bookings.reduce((sum, booking) => sum + booking.total_price, 0);

  // 最近预订
  const recentBookings = bookings
    .slice(0, 5)
    .map((booking) => ({
      ...booking,
      key: booking.id,
      passengerName: booking.passenger ? `${booking.passenger.first_name} ${booking.passenger.last_name}` : '未知',
      flightNumber: booking.flight?.flight_number || '未知',
    }));

  const bookingColumns = [
    {
      title: '预订号',
      dataIndex: 'booking_number',
      key: 'booking_number',
    },
    {
      title: '乘客',
      dataIndex: 'passengerName',
      key: 'passengerName',
    },
    {
      title: '航班',
      dataIndex: 'flightNumber',
      key: 'flightNumber',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status) => {
        const colorMap = {
          confirmed: 'green',
          pending: 'orange',
          cancelled: 'red',
        };
        const textMap = {
          confirmed: '已确认',
          pending: '待确认',
          cancelled: '已取消',
        };
        return <Tag color={colorMap[status]}>{textMap[status]}</Tag>;
      },
    },
    {
      title: '金额',
      dataIndex: 'total_price',
      key: 'total_price',
      render: (price) => `¥${price}`,
    },
  ];

  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 24 }}>
        <h1>仪表盘</h1>
        <Button 
          type="primary" 
          icon={<PlusOutlined />}
          onClick={() => navigate('/bookings/create')}
        >
          创建预订
        </Button>
      </div>
      
      {/* 统计卡片 */}
      <Row gutter={16} style={{ marginBottom: 24 }}>
        <Col span={6}>
          <Card>
            <Statistic
              title="总航班数"
              value={totalFlights}
              prefix={<RocketOutlined />}
              valueStyle={{ color: '#1890ff' }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="总乘客数"
              value={totalPassengers}
              prefix={<UserOutlined />}
              valueStyle={{ color: '#52c41a' }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="总预订数"
              value={totalBookings}
              prefix={<BookOutlined />}
              valueStyle={{ color: '#faad14' }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="总收入"
              value={totalRevenue}
              precision={2}
              prefix={<DollarOutlined />}
              valueStyle={{ color: '#722ed1' }}
            />
          </Card>
        </Col>
      </Row>

      {/* 最近预订 */}
      <Card title="最近预订" style={{ marginBottom: 24 }}>
        <Table
          columns={bookingColumns}
          dataSource={recentBookings}
          pagination={false}
          size="small"
        />
      </Card>

      {/* 系统状态 */}
      <Row gutter={16}>
        <Col span={12}>
          <Card title="航班状态分布">
            <Row>
              <Col span={12}>
                <div style={{ textAlign: 'center' }}>
                  <h3>已安排</h3>
                  <p style={{ fontSize: 24, color: '#1890ff' }}>
                    {flights.filter(f => f.status === 'scheduled').length}
                  </p>
                </div>
              </Col>
              <Col span={12}>
                <div style={{ textAlign: 'center' }}>
                  <h3>已起飞</h3>
                  <p style={{ fontSize: 24, color: '#52c41a' }}>
                    {flights.filter(f => f.status === 'departed').length}
                  </p>
                </div>
              </Col>
            </Row>
          </Card>
        </Col>
        <Col span={12}>
          <Card title="预订状态分布">
            <Row>
              <Col span={8}>
                <div style={{ textAlign: 'center' }}>
                  <h3>已确认</h3>
                  <p style={{ fontSize: 24, color: '#52c41a' }}>
                    {bookings.filter(b => b.status === 'confirmed').length}
                  </p>
                </div>
              </Col>
              <Col span={8}>
                <div style={{ textAlign: 'center' }}>
                  <h3>待确认</h3>
                  <p style={{ fontSize: 24, color: '#faad14' }}>
                    {bookings.filter(b => b.status === 'pending').length}
                  </p>
                </div>
              </Col>
              <Col span={8}>
                <div style={{ textAlign: 'center' }}>
                  <h3>已取消</h3>
                  <p style={{ fontSize: 24, color: '#ff4d4f' }}>
                    {bookings.filter(b => b.status === 'cancelled').length}
                  </p>
                </div>
              </Col>
            </Row>
          </Card>
        </Col>
      </Row>
    </div>
  );
};

export default Dashboard;